<?php

namespace app\common\model;

use app\beautiful\model\finance\AccountBalanceModel;
use app\beautiful\model\finance\SettlementModel;
use app\beautiful\model\finance\WithdrawModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\order\BuyOrderModel;
use app\beautiful\model\partner\BonusModel;
use app\common\model\account\ShopAccountModel;
use app\stores\model\order\GoodsOrderModel;
use think\facade\Db;


class ShopBalanceLogsModel extends CommonModel{

    protected  $name = 'beautiful_shop_balance_logs';

    protected  $pk   = 'shop_balance_logs_id';

    public static function up($data,$where){
//        $data['edit_time']=date('Y-m-d H:i:s');
        $res=self::update($data,$where);
        return $res;
    }

    /**
     * @param $money  奖励金额
     * @param $status  状态：-1减少，1增加
     * @param $shop_id 门店Id
     * @param $id  订单id
     * @param int $type 类型：1下单，2买单
     * @return ShopBalanceLogsModel|int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function in($money,$status,$shop_id,$id,$type=1,$money_status=0,$fields='account_money'){
        $AccountBalanceModel=new AccountBalanceModel();
//        if($status==-1){
//            $money='-'.$money;
//        }
        $account_info=$AccountBalanceModel->where(['shop_id'=>$shop_id,'is_delete'=>0])->find();
        $insert=[];
        $insert['shop_id']=$shop_id;
        $insert['type']=$status;
        $insert['status']=$money_status;
        $insert['balance_type']=1;
        $insert['from_type']=2;
        $insert['before_balance']=$account_info[$fields];
        $insert['balance']=$money;
        $insert['after_balance']=($account_info[$fields]+$money);
        if($status==-1){
            $insert['balance']='-'.$money;
            $insert['after_balance']=($account_info[$fields]-$money);
        }
        $where=[];
        $where['type']=$status;
        $where['shop_id']=$shop_id;
        switch ($type){
            case 1:
                $order=GoodsOrderModel::where(['order_id'=>$id])->find();
                $insert['order_id']=$id;
                $where['order_id']=$id;
                break;
            case 2:
                $order=BuyOrderModel::where(['buy_order_id'=>$id])->find();
                $insert['b_order_id']=$id;
                $where['b_order_id']=$id;
                break;
        }
        if(!empty($order)){
            $insert['member_id']=$order['member_id'];
        }
        if($type==3){
            $where['settle_time']=date('Y-m-d',strtotime('-1 day'));
            $insert['settle_time']=date('Y-m-d',strtotime('-1 day'));
            $insert['balance_type']=2;//每日结算
            $where['balance_type']=2;//每日结算
        }
        if($type==4){
            $insert['bonus_id']=$id;//股东分红奖金退回
            $insert['balance_type']=3;//股东分红奖金退回
            $where['balance_type']=3;//股东分红奖金退回
            $where['bonus_id']=$id;//股东分红奖金退回
        }
        $insert['add_time']=date('Y-m-d H:i:s');
        $info=self::where($where)->find();
        $res=false;
        if(empty($info)){
            $res=self::insertGetId($insert);
            if($status==-1){
                $AccountBalanceModel->n_dec(['shop_id'=>$shop_id],$fields,$money);
            }elseif($status==1 && $money_status==1){
                $AccountBalanceModel->n_inc(['shop_id'=>$shop_id],$fields,$money);
            }
        }else{
            if($status==1 && $money_status==1){
                unset($insert['add_time']);
                $insert['edit_time']=date('Y-m-d H:i:s');
                $insert['status']=1;
                self::up($insert,['shop_balance_logs_id'=>$info['shop_balance_logs_id']]);
                $AccountBalanceModel->n_inc(['shop_id'=>$shop_id],$fields,$money);
            }
        }
        return $res;
    }

    public function getList($where,$money_where,$order,$page=0,$limit=0){
        $query = $this->alias('ml')->join('shop s','ml.shop_id=s.shop_id')
            ->when(!empty($where['member_id']),function ($query) use ($where){
                $query->where(['ml.member_id'=>$where['member_id']]);
            })
            ->when(!empty($where['type']),function ($query) use ($where){
                $query->where('ml.type','=',$where['type']);
            })
            ->when(isset($where['status']),function ($query) use ($where){
                $query->where('ml.status','=',$where['status']);
            })
            ->when(isset($where['money_status']),function ($query) use ($where){
                $query->where(['ml.money_status'=>$where['money_status']]);
            })
            ->when(!empty($where['add_start_time']),function ($query) use ($where){
                $query->where('ml.add_time','>=',$where['add_start_time']);
            })
            ->when(!empty($where['add_end_time']),function ($query) use ($where){
                $query->where('ml.add_time','<=',$where['add_end_time']);
            })->field("ml.type,ml.status,ml.money_status,ml.g_order_id,ml.money,ml.add_time,s.name as shop_name");
        $count = $query->count();
        $query = $query->order($order);
        if($page>0) $query = $query->page($page);
        if($limit>0) $query = $query->limit($limit);
        $list = $query->select()->toArray();

        $out_money = $this->where($money_where)->where(['status'=>0])->sum('money');
        $out_money = sprintf("%.2f", $out_money);
        $income_money = $this->where($money_where)->where(['status'=>1])->sum('money');
        $income_money = sprintf("%.2f", $income_money);

        if(!empty($list)){
            foreach ($list as $k=>$v){
                if($v['type']==4){
                    $goods_order = GoodsOrderModel::user_order(['order_id'=>$v['g_order_id']]);
                }
                $list[$k]['tg_member_name'] = isset($goods_order)?$goods_order['nick_name']:null;
            }
        }

        return compact('count','list','out_money','income_money');
    }
    public static function list($where,$order=['a.shop_balance_logs_id'=>'desc'],$page=1,$limit=10){
        $query = Db::name('beautiful_shop_balance_logs')->alias('a')
            ->join('beautiful_member c','a.member_id=c.member_id')
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['a.shop_id'=>$where['shop_id']]);
            })
            ->when(isset($where['member_id']),function ($query) use ($where){
                $query->where(['a.member_id'=>$where['member_id']]);
            })
            ->when(isset($where['status']),function ($query) use ($where){
                $query->where(['a.status'=>$where['status']]);
            })
            ->when(isset($where['balance_type']),function ($query) use ($where){
                $query->where(['a.balance_type'=>$where['balance_type']]);
            })
            ->when(!empty($where['start_time']),function ($query) use ($where){
                $query->where('a.add_time','>=',$where['start_time']);
            })
            ->when(!empty($where['end_time']),function ($query) use ($where){
                $query->where('a.add_time','<=',$where['end_time']);
            })
            ->field("a.*,c.nick_name,c.member_num");
        $count=$query->count();
        $list=$query->order($order)
            ->limit($limit)->page($page)
            ->select()
            ->toArray();
        return compact('count','list');
    }
    public static function plist($where,$order=['a.id'=>'desc'],$page=1,$limit=10){
        $query = Db::name('member_money_detail')->alias('a')
            ->leftJoin('beautiful_order b','a.g_order_id=b.order_id and a.g_order_id>0')
            ->leftJoin('beautiful_member c','b.member_id=c.member_id and a.g_order_id>0')
            ->leftJoin('beautiful_buy_order d','a.b_order_id=d.buy_order_id and a.b_order_id>0')
            ->leftJoin('beautiful_member e','d.member_id=e.member_id and a.b_order_id>0')
            ->leftJoin('beautiful_partner_bonus f','a.partner_bonus_id=f.partner_bonus_id and a.partner_bonus_id>0')
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['a.shop_id'=>$where['shop_id']]);
            })
            ->when(isset($where['member_id']),function ($query) use ($where){
                $query->where(['a.member_id'=>$where['member_id']]);
            })
            ->when(isset($where['partner_id']),function ($query) use ($where){
                $query->where(['a.partner_id'=>$where['partner_id']]);
            })
            ->when(isset($where['types']),function ($query) use ($where){
                $query->where('a.type','In',$where['types']);
            })
            ->when(isset($where['status']),function ($query) use ($where){
                $query->where(['a.status'=>$where['status']]);
            })
            ->field("a.id,a.add_time,a.type,c.nick_name as g_nick_name,e.nick_name as b_nick_name,a.money,f.start_time,f.end_time");
        $count=$query->count();
        $list=$query->order($order)
            ->limit($limit)->page($page)
            ->select()
            ->toArray();
        return compact('count','list');
    }
    public static function dlist($where,$order=['a.shop_balance_logs_id'=>'desc'],$page=1,$limit=10){
        $query = Db::name('beautiful_shop_balance_logs')->alias('a')
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['a.shop_id'=>$where['shop_id']]);
            })
            ->when(isset($where['status']),function ($query) use ($where){
                $query->where(['a.status'=>$where['status']]);
            })
            ->when(isset($where['balance_type']),function ($query) use ($where){
                $query->whereIn('a.balance_type',$where['balance_type']);
            })
            ->when(!empty($where['start_time']),function ($query) use ($where){
                $query->where('a.add_time','>=',$where['start_time']);
            })
            ->when(!empty($where['end_time']),function ($query) use ($where){
                $query->where('a.add_time','<=',$where['end_time']);
            })
            ->field("a.*");
        $count=$query->count();
        $list=$query->order($order)
            ->limit($limit)->page($page)
            ->select()
            ->toArray();
        if(!empty($list)){
            foreach ($list as $k=>$v){
                $list[$k]['settlement_id'] = 0;
                $list[$k]['bonus'] = $list[$k]['withdraw'] = (object) null;
                if($v['balance_type']==2){
                    $settlement = SettlementModel::where(['shop_id'=>$v['shop_id'],'settlement_time'=>$v['settle_time'],'is_delete'=>0])->find();
                    $list[$k]['settlement_id'] = $settlement['settlement_id'];
                }
                if($v['balance_type']==3){
                    $bonus = BonusModel::where(['shop_id'=>$v['shop_id'],'bonus_id'=>$v['bonus_id'],'is_delete'=>0])->find();
                    if($bonus){
                        $list[$k]['bonus'] = $bonus;
                        $list[$k]['bonus']['balance'] = $v['balance'];
                        $list[$k]['bonus']['status'] = $v['status'];
                    }
                }
                if($v['balance_type']==4){
                    $withdraw= WithdrawModel::info(['withdraw_id'=>$v['withdraw_id']],'w.*,wa.type as account_type,wa.open_bank_name,wa.open_branch,wa.account_name,wa.account_number');
                    $list[$k]['withdraw'] = $withdraw;
                }
            }
        }
        return compact('count','list');
    }
}

